package com.xhb.campusservices.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xhb.campusservices.common.lang.Result;
import com.xhb.campusservices.enums.AuditState;
import com.xhb.campusservices.enums.OrderState;
import com.xhb.campusservices.enums.TaskState;
import com.xhb.campusservices.pojo.Orders;
import com.xhb.campusservices.pojo.Task;
import com.xhb.campusservices.pojo.Tasktype;
import com.xhb.campusservices.pojo.orderDto.Complete;
import com.xhb.campusservices.pojo.teskDto.TaskManagement;
import com.xhb.campusservices.service.OrderService;
import com.xhb.campusservices.service.TaskMService;
import com.xhb.campusservices.service.TaskService;
import com.xhb.campusservices.service.TasktypeService;
import com.xhb.campusservices.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 任务管理
 */
@Slf4j
@RestController
@RequestMapping("/task")
@Validated
public class TaskController {

    @Autowired
    TaskService taskService;

    @Autowired
    TasktypeService tasktypeService;

    @Autowired
    TaskMService taskMService;

    @Autowired
    OrderService orderService;

    @Autowired
    JWTUtils jwtUtils;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 任务类型
     *
     * @return
     */
    @GetMapping("/taskType")
    public Result taskType() {
        List<Tasktype> list = tasktypeService.list();
        return Result.succ(list);
    }

    /**
     * 发布任务
     *
     * @param task
     * @return
     */
    @PostMapping("/releaseTask")
    public Result releaseTask(@Validated @RequestBody Task task, HttpServletRequest request) {

       /* if (task.getTaskreward() == null) {
            return Result.fail("任务酬劳不能为空");
        }*/

        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(task.getUserid()).equals(jwtUtils.getUserId(token))) {
            try {
                //设置发布时间为当前时间
                task.setReleasetime(sdf.parse(sdf.format(new Date())));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if (taskService.save(task)) {
                return Result.succ(200, "发布成功", task);
            } else {
                return Result.fail("发布失败");
            }
        } else {
            return Result.fail(403, "没有发布权限!");
        }
    }

    /**
     * 任务管理(未接任务)
     *
     * @return
     */
    @GetMapping("/taskManagement")
    public Result taskManagement() {
        List<TaskManagement> taskManagements = taskMService.taskManagementList();
        if (taskManagements.size() == 0) {
            return Result.succ(200, "大厅还没有任务哦~", null);
        }
        return Result.succ(taskManagements);
    }


    /**
     * 我的发布
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/allTasks/{userId}")
    public Result allTasks(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(userId).equals(jwtUtils.getUserId(token))) {
            LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Task::getUserid, userId)
                    .ne(Task::getTaskstate, TaskState.已删除)
                    .orderByDesc(Task::getReleasetime);
            List<Task> list = taskService.list(queryWrapper);
            if (list.size() == 0) {
                return Result.succ(200, "主人，您还没有发布任务哦~", null);
            }
            return Result.succ(list);
        }
        return Result.fail(403, "没有查看权限");
    }

    /**
     * 删除任务
     *
     * @param deleteT
     * @param request
     * @return
     */
    @PostMapping("/deletedTask")
    public Result deletedTask(@Validated @RequestBody Complete deleteT, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(deleteT.getUserId()).equals(jwtUtils.getUserId(token))) {
            Task byId = taskService.getById(deleteT.getId());
            LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();

            //只有当任务状态是“已被接单并已完成”或者“未接单”才可以被删除
            if (byId.getTaskstate() == TaskState.已被接单) {

                LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Orders::getTaskid, deleteT.getId());
                Orders one = orderService.getOne(queryWrapper);
                //只有当订单状态是“已完成”才可以被删除，否则删除失败
                if (one.getOrderstate() == OrderState.已完成) {
                    updateWrapper.eq(Task::getId, deleteT.getId())
                            .set(Task::getTaskstate, TaskState.已删除)
                            .set(Task::getReleasetime, sdf.format(new Date()));
                    if (taskService.update(updateWrapper)) {
                        return Result.succ(200, "删除成功", null);
                    }
                    return Result.fail("删除失败");
                }

                return Result.fail("订单还未完成，删除失败");

            } else if (byId.getTaskstate() == TaskState.已发布) {
                if (taskService.removeById(deleteT.getId())) {
                    return Result.succ(200, "删除成功", null);
                }
            }
        }
        return Result.fail(403, "没有删除权限");
    }
}
